import {KeyboardAwareScrollView} from '@codler/react-native-keyboard-aware-scroll-view';
import React, {forwardRef, PropsWithChildren} from 'react';
import {
  FlatList,
  FlatListProps,
  RefreshControl,
  RefreshControlProps,
  SafeAreaView,
  ScrollViewProps,
  StyleSheet,
  View,
  ViewProps,
} from 'react-native';
import {STYLE_COLOR} from '../../variables';

export type BackGroundProps<Props> = PropsWithChildren<Props> & {
  white?: boolean;
};

const styles = StyleSheet.create({
  background: {
    backgroundColor: STYLE_COLOR.CONTAINER_BACKGROUND,
    flex: 1,
  },
  whiteBackground: {
    backgroundColor: STYLE_COLOR.CONTENT_BACKGROUND,
    flex: 1,
  },
});
// 写几遍
export const BGView = ({
  white,
  style,
  ...props
}: BackGroundProps<ViewProps>) => {
  return (
    <View
      style={[white ? styles.whiteBackground : styles.background, style]}
      {...props}
    />
  );
};

export const BGSafe = ({
  style,
  white,
  ...props
}: BackGroundProps<ViewProps>) => {
  return (
    <SafeAreaView
      style={[white ? styles.whiteBackground : styles.background, style]}
      {...props}
    />
  );
};

const Refresh = (props: RefreshControlProps) => {
  return <RefreshControl {...props} />;
};

export const BGScroll = forwardRef<
  KeyboardAwareScrollView,
  BackGroundProps<ScrollViewProps> & Partial<RefreshControlProps>
>(({style, white, refreshing, onRefresh, ...props}, ref) => {
  return (
    <KeyboardAwareScrollView
      ref={ref}
      style={[white ? styles?.whiteBackground : styles?.background, style]}
      refreshControl={
        refreshing !== undefined ? (
          <Refresh refreshing={refreshing} onRefresh={onRefresh} />
        ) : undefined
      }
      keyboardShouldPersistTaps="handled"
      contentInsetAdjustmentBehavior="automatic"
      contentContainerStyle={{paddingBottom: 16}}
      scrollIndicatorInsets={{right: 1}}
      {...props}
    />
  );
});

export const BGList = <T,>({
  white,
  style,
  ...props
}: BackGroundProps<FlatListProps<T>>) => {
  return (
    <FlatList
      keyboardShouldPersistTaps="handled"
      style={[white ? styles.whiteBackground : styles.background, style]}
      keyExtractor={(_, idx) => idx.toString()}
      contentInsetAdjustmentBehavior="automatic"
      scrollIndicatorInsets={{right: 1}} // https://github.com/facebook/react-native/issues/26610
      {...props}
    />
  );
};
